<template>
  <div class="courseware-container">
      <el-card class="box-card">
        <div slot="header" class="hader-view">
          <span class="name">我的课程</span>
          <div>
            <div class="btn-view">
                <el-input placeholder="搜索" style="width:400px"
                @keyup.enter="btnQuery"
                 clearable v-model="queryName">
                   <el-button slot="append" icon="el-icon-search" @click="btnQuery"></el-button>
                </el-input>
                <el-button style="margin-left:10px" @click="btnAdd" class="el-icon-plus" type="primary">添加课件</el-button>
            </div>
          </div>
        </div>
        <div class="card-context"     v-loading="loading">
            <div class="card-list" v-if="tableList.length>0">
                <el-card class="item-card" v-for="item in tableList" :key="item.courseId">
                  <div slot="header" class="hader-item">
                
                    <el-tooltip  effect="dark" :content="item.categoryUrl.substr(1)" placement="top-start">
                      <div class="title-name">{{item.categoryUrl.substr(1)}}</div>
                        </el-tooltip>
                  <div class="delete">
                    <el-link type="danger" @click="btnDel(item)"  icon="el-icon-delete"></el-link>
                  </div>
                </div>
                <div class="btnPaly" title="点击打开课件" style="cursor: pointer;" v-if="item.enableStatus===0" @click="btnOpen(item)">
                    <el-image 
                      style="width: 240px; height: 100px"
                      :src="item.fileImg" 
                      :fit="'cover'">
                    </el-image>
                    <div class="name">
                      {{ item.name.split('.')[0] }}
                    </div>
                   <i class="el-icon-video-play iconbtn"></i>
                  </div>
                  <div class="nobtnPaly" title="该课件已禁用" style="cursor: pointer;" v-else >
                    <el-image 
                      style="width: 240px; height: 100px"
                      :src="item.fileImg" 
                      :fit="'cover'">
                    </el-image>
                    <div class="name">
                      {{ item.name.split('.')[0] }}
                    </div>
                   <i class="el-icon-video-play iconbtn"></i>
                  </div>
              </el-card>
            </div>
            <el-empty v-else description="您还没有创建任何课程，点击“添加课程”按钮创建属于您的课程吧！"></el-empty>
          <el-pagination v-if="total>20"
            background
            layout="total,prev,sizes, pager, next"
            :current-page.sync="pageSize"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :total="total">
          </el-pagination>
        </div>
      </el-card>
      <el-dialog
        title="文档"
         :visible.sync="openWebOffice"
         :fullscreen="fullscreen"
          :before-close="wxClose"
          :show-close="false"
          top="0"
         :close-on-click-modal="false"
        width="100%">
         <template slot="title">
          <div class="open-title-view">
           <img src="../../assets/login/clogo1.png" style="height:40px"> 
            <span style="border-left:1px solid #ddd;padding-top:5px;padding-left:10px"> {{openData?openData.name.split('.')[0]:''}}</span>
           <template v-if="!openType">
            <div class="video-view" @click="btnPlay">

              <i :class="clickType?'el-icon-video-play':'el-icon-switch-button'" 
              style="color:#30ab74;font-size:22px;padding-right:6px"
              :style="{color:clickType?'#30ab74':'#F56C6C'}"
              ></i> {{clickType?'开始授课':'退出播放'}} 
              </div>
              <span class="btnExit" @click="wxClose"><i class="el-icon-eleme" style="color:#F56C6C;font-size:16px"></i> 退出</span>
          </template>
          </div>
        </template>
        <div class="demo" v-if="openType">
          <div class="item el-icon-arrow-left" title="上一页" @click="onPre(-1)"></div>
          <div class="item el-icon-arrow-right" title="下一页"  @click="onNext(1)"></div>
          <div class="item" :class="clickType?'el-icon-video-play':'el-icon-switch-button'" 
           :style="{color:clickType?'#30ab74':'#F56C6C'}" :title="clickType?'开始授课':'退出播放'" @click="btnPlay"></div>
      </div>
      <div class="dome-left" v-if="openType">
          <div class="item el-icon-arrow-left" title="上一页" @click="onPre(-1)"></div>
          <div class="item el-icon-arrow-right" title="下一页"  @click="onNext(1)"></div>
          <div class="item" :class="clickType?'el-icon-video-play':'el-icon-switch-button'" 
           :style="{color:clickType?'#30ab74':'#F56C6C'}" :title="clickType?'开始授课':'退出播放'" @click="btnPlay"></div>
      </div>
      <div v-if="openWebOffice" id="webOffice" :style="{width:'100%',height:winHeight+'px'}"></div>
     </el-dialog>
      <el-dialog
        title="请选择需要的课件"
        :visible.sync="dialogVisible">
      <el-form :model="ruleForm"  size="medium" style="padding:20px 0" :rules="rules" ref="ruleForm" label-width="60px">
        <el-form-item label="分类">
            <el-cascader-panel 
            :options="treeData"
            @change="handleChange"
            :props="{ 
              children: 'children',
              label: 'name',
              value:'categoryId',
              checkStrictly:true 
              }"></el-cascader-panel>
        </el-form-item>
        <el-form-item label="课件" prop="courseId">
          <el-select v-model="ruleForm.courseId" clearable placeholder="请选择">
            <el-option
              v-for="item in optionsList"
              :key="item.courseId"
              :label="item.name"
              :value="item.courseId">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
            <el-button  size="medium" icon="el-icon-close" @click="dialogVisible = false">取 消</el-button>
            <el-button type="primary" icon="el-icon-finished"  size="medium"
                       @click="submitForm('ruleForm')">确 定</el-button>
          </span>
    </el-dialog>
  </div>
</template>
<script>
import {getUserCourseList,addCourse,getValidCourseList,delCourse,courseTime,getCourseInfo} from '@/api/clientManage'
import {getCategoryTree} from '@/api/teachManage'
import WebOfficeSDK from '@/sdk/web-office-sdk-solution-v2.0.4.es.js'
  let instance=null
export default {
  data() {
    return {
     queryName:'',
     ruleForm: {courseId:''},
     rules: {
          courseId: [
            { required: true, message: '请选择课件', trigger: 'blur' }
          ]
      },
      dialogVisible: false,
      openWebOffice:false,
      fullscreen:false,
       winHeight:document.documentElement.clientHeight,
       treeData:[],
       tableList:[],
       optionsList:[],
       loading:null,
       total:0,
       limit:20,
       pageSize:1,
      countdown: 1,
      // 定时器
      timer: null,
      openData:null,
      playType:0,
      clickType:true,
      openType:false
    }
  },
  computed: {},
  created() {
    this.getList()
    this.getTreeList()
    window.addEventListener("keydown",(e)=>{
      if(e.key=='Enter'||e.key=='enter'){
        this.btnQuery()
      }
    },true) 
  },
  methods: {
    getList(){
      this.loading = true
     getUserCourseList({
        "limit": this.limit,
        "page": this.pageSize,
        name:this.queryName
     }).then((res)=>{
       this.tableList = res.data
       this.total = res.total
       this.loading = false
     })
    },
    handleSizeChange(val) {
        this.limit=val
        this.getList()
      },
      handleCurrentChange(val) {
         this.pageSize=val
        this.getList()
      },
    getChildren(list){
      if(list.length){
       return  list.map((item)=>{
          if(item.children.length){
            item.children= this.getChildren(item.children)
          }else{
            item.children =null
          }
        return item
       })
      }else{
        return []
      }
    },
    getTreeList(){
      getCategoryTree({
        "limit": 999,
        "name": "",
        "orderField": "",
        "orderType": "",
        "page": 1
      }).then((res)=>{
        if(res.code===0){
          this.treeData = this.getChildren(res.data)
        }
      })
    },
    getSelectList(categoryId){
      getValidCourseList(categoryId).then((res)=>{
        if(res.code===0){
          this.optionsList = res.data
        }else{
          this.optionsList =[]
        }
      })
    },
    handleChange(data){
      this.ruleForm.courseId=''
      if(data && data.length>0){
        this.getSelectList(data[data.length-1])
      }
     },
    btnQuery(){
      this.getList()
    },
    getType(item){
      // 文字（Word）：doc、docx、wps 等后缀文件
      // 表格（Excel）：xls、xlsx 等后缀文件
      // 演示（PPT）：ppt、pptx 等后缀文件
      // PDF：pdf 等后缀文件

      let word = ['doc','docx','pws'];
      if(word.indexOf(item.localPath.split('.')[1].toLowerCase())>=0){
        return 'w'
      }
      let excel =['xls','xlsx']
        if(excel.indexOf(item.localPath.split('.')[1].toLowerCase())>=0){
        return 's'
      }
      let ppt =['ppt','pptx']
        if(ppt.indexOf(item.localPath.split('.')[1].toLowerCase())>=0){
        return 'p'
      }

      let pdf=['pdf']
        if(pdf.indexOf(item.localPath.split('.')[1].toLowerCase())>=0){
        return 'f'
      }
      return 'w'
     
    },
    reckonTime() {
      // 验证码60秒倒计时
      this.timer = setInterval(() => {
       this.countdown++;
      }, 1000)
    },
     wxClose(){
      if(this.timer){
       window.clearInterval(this.timer)
      }
      this.openWebOffice = false
     this.openType = false
      if(this.openData){
      courseTime({
          "time": this.countdown,
          "type": this.playType,
          "userCourseId":this.openData.userCourseId
      }).then((res)=>{
        console.log(res)
      })
      }
    },
    async openOnLineWebOffice (item){
     this.countdown=1
     this.playType =0
     this.reckonTime() 
     
     instance = await WebOfficeSDK.init({
      officeType: this.getType(item),
       appId: (window.location.origin.indexOf('amaze.cqtancheng.com')>=0?'AK20230825QGRISX':'SX20230719TBXNMT'),
       fileId: item.courseId,
       mode:'simple',//this.getType(item)==='p'?'simple':'normal',
       mount:document.querySelector("#webOffice"),
       pptOptions: {
        isShowBottomStatusBar: false, // 是否展示底部状态栏
        isShowRemarkView: true, // 是否显示备注视图
        isShowInsertMedia: true, // 是否显示插入音视频入口
        isShowComment: true, // 是否显示评论相关入口
      }
    })
     if(this.getType(this.openData)==='f'){
      //播放监听
        instance.ApiEvent.AddApiEventListener('StartPlay', data => {
            this.playType =1
          this.clickType =false
          })
        //退出播放监听
        instance.ApiEvent.AddApiEventListener('EndPlay', data => {
          this.playType =1
          this.clickType =true
          this.wxClose()
        })
        await instance.ready()
        // 控制目录的显示隐藏
        instance.Application.ActivePDF.DocumentMap = true

     }else{
        //播放监听
        instance.ApiEvent.AddApiEventListener('SlideShowBegin', data => {
            this.playType =1
          this.clickType =false
          })
        //退出播放监听
        instance.ApiEvent.AddApiEventListener('SlideShowEnd', data => {
          this.playType =1
          this.wxClose()
          this.clickType =true
        })
     }
    },
    requestFullScreen(element,type) { 
      let requestMethod =null
      if(type===1){
         requestMethod = element.requestFullScreen || element.webkitRequestFullScreen || element.mozRequestFullScreen || element.msRequestFullScreen; 

      }else{
        requestMethod = element.exitFullscreen || element.webkitCancelFullScreen || element.mozCancelFullScreen || element.msExitFullscreen; 
      }
     
      if (requestMethod) { 
        requestMethod.call(element); 
      } else if (typeof window.ActiveXObject !== "undefined") { 
        let wscript = new ActiveXObject("WScript.Shell"); 
        if (wscript !== null) { 
          wscript.SendKeys("{F11}"); 
        } 
      }
   },
    btnPlay(){
        if(this.getType(this.openData)==='f'){
           setTimeout(async () => {
              await instance.ready()
              if(this.clickType){
                this.openType = true
                await instance.Application.ActivePDF.StartPlay('active', true, true)
                
              }else{
                await instance.Application.ActivePDF.EndPlay()
                this.openType = false
                 // 控制目录的显示隐藏
                instance.Application.ActivePDF.DocumentMap = true
              }
           }, 100)
       }else{
          setTimeout(async () => {
              await instance.ready()
                  
              if(this.clickType){
                this.openType = true
                this.requestFullScreen(document.querySelector("#webOffice"),1)
                await instance.Application.ActivePresentation.SlideShowSettings.Run()
              }else{
                this.openType = false
                this.requestFullScreen(document.querySelector("#webOffice"),2)
                await instance.Application.ActivePresentation.SlideShowWindow.View.Exit()
              }
            }, 100)
      }
    },
    btnOpen(item){
      this.openWebOffice =true
      this.openData = item
       getCourseInfo({userCourseId:item.courseId}).then((res)=>{
        setTimeout(() => {
          this.openOnLineWebOffice(item)
       }, 200);
      })
    
    },
    async  jumpToPage(page) {
      await instance.ready()
      const app = instance.Application
      // 获取当前页数和总页数
      const [curryPage, totalPages] = await Promise.all([
        app.ActivePDF.CurrentPage,
        app.ActivePDF.PagesCount
      ])
      // page > 0，下一页， page < 0，上一页
      let targetPage = curryPage + page
      if (targetPage > totalPages) {
        targetPage = 1
      }

      await app.ActivePDF.JumpToPage(targetPage)
    },
    async  onPre(page) {
       if(this.getType(this.openData)==='p'){
          await instance.ready()
          const app = instance.Application
          // 切换到 PPT 全屏播放状态
          await app.ActivePresentation.SlideShowSettings.Run()
          // 切换到下一步动画
          await app.ActivePresentation.SlideShowWindow.View.GotoPreClick()
       }else{
        this.jumpToPage(page)
       }
    },
    async  onNext(page) {
       if(this.getType(this.openData)==='p'){
            await instance.ready()
            const app = instance.Application
            // 切换到 PPT 全屏播放状态
            await app.ActivePresentation.SlideShowSettings.Run()

            // 切换到下一步动画
            await app.ActivePresentation.SlideShowWindow.View.GotoNextClick()
       }else{
          this.jumpToPage(page)
       }
    },
     btnDel(item){
        this.$confirm('您确定要删除该课件？', '消息提示', {
        }).then(() => {
          delCourse([item.userCourseId]).then((res)=>{
            if(res.code===0){
              this.$message.success("删除成功");
              this.getList()
            }else {
                  this.$message.error(res.message||"操作失败");
                }
          })
        }).catch(action => {
        });
     },
     btnAdd(){
       this.dialogVisible=true
     },
    submitForm(formName) {
       this.$refs[formName].validate((valid) => {
          if (valid) {
            addCourse({courseId:this.ruleForm.courseId}).then((res) => {
                if (res.code === 0) {
                  this.$message.success("添加成功");
                  this.getList()
                  this.dialogVisible = false;
                } else {
                  this.$message.error(res.message||"操作失败");
                }
              });
          }
        });

    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    }
  }
}
</script>

<style lang="scss">
.box-card .el-card__header{
  padding:10px 20px;
}
.el-dialog__body{
  padding:0 10px;
}
  .open-title-view{
    position: relative;
    display: flex;
    align-items: center;
    font-size: 14px;
    .open{
      position: absolute;
      right: 20px;
      cursor: pointer;
    }
    .video-view{
      height:40px;
      width:120px;
      text-align: center;
      font-size:15px;
      line-height:40px;
      position: absolute;
      left:50%;
      margin-left:-60px;
      cursor: pointer;
      top:50%;
      margin-top:-20px;
      display: flex;
      align-items: center;
    }
    .btnExit{
      position: absolute;
      right: 20px;
      cursor: pointer;
      font-size:15px;
    }
  }
  .nobtnPaly,
  .btnPaly{
    padding:10px;
    cursor: pointer;
    border:1px solid #fff;
    border-radius:4px;
    .name{
      font-size:15px;
      color: #333;
      padding-top:10px;
    }
    .iconbtn{
        margin-right: 5px;
        position: absolute;
        top: 50%;
        left: 50%;
        font-size: 40px;
        color: transparent;
        height: 50px;
        width: 50px;
        margin-top: -8px;
        margin-left: -20px;
    }
  }
  .nobtnPaly{
      background-color: #eeeeee59;
    .name{
      color: #888;
    }
    .iconbtn{
      color: transparent;
    }
  }
  .btnPaly:hover{
        border:1px solid #30ab74;
         .name{
            color: #30ab74;
        }
    .iconbtn{
      color: #30ab74;
    }
  }
.courseware-container {
  padding: 10px;
  box-sizing: border-box;
  height: calc(100vh - 54px);
  .card-context{
     height: calc(100vh - 84px);
    overflow-y: auto;
    padding-bottom:100px;
  }
  .box-card{
    .card-list{
      display: flex;
      justify-content: flex-start;
      flex-wrap: wrap;
    }
    .item-card{
      width:300px;
      margin-left:10px;
      margin-bottom:10px;
      position: relative;
      .delete{
        position: absolute;
        right:10px;
        z-index: 9;
      }
    }
  }

  .hader-view {
    display: flex;
    align-items: center;
    justify-content: space-between;
    .name{
      font-weight: bold;
      font-size:15px;
      overflow: hidden;
      width:100%;
    }
    .btn-view{
      display: flex;
    }
  }
  .hader-item{
    display: flex;
    align-items: center;
    justify-content: space-between;

    .title-name{
      overflow: hidden;
      white-space: nowrap;
      width:240px;
      text-overflow: ellipsis;
      -webkit-line-clamp: 1;
      font-size:12px;
    }

  }
}
.dome-left,
  .demo {
    position: fixed;
    right: 20px;
    z-index: 997;
    width: 40px;
    height: 150px;
    top:50%;
    margin-top:-50px;
    background-color: #fff;
    border-radius:4px;
    .item{
      text-align: center;
      height:50px;
      line-height:50px;
      cursor: pointer;
      width:40px;
      font-size:20px;
    }
  }
.dome-left{
  right: auto;
  left:0;
}
</style>
